/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.eningqu.aipen.demo.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eningqu.aipen.demo.PenCtrlSdkManager;
import com.eningqu.aipen.demo.R;
import com.eningqu.aipen.demo.adapter.DeviceAdapter;
import com.eningqu.aipen.demo.common.Const;
import com.eningqu.aipen.sdk.ErrorCode;
import com.eningqu.aipen.sdk.NQPenSDK;
import com.eningqu.aipen.sdk.bean.device.NQBtDevice;
import com.eningqu.aipen.sdk.bean.device.NQDeviceBase;
import com.eningqu.aipen.sdk.bean.device.NQUsbDevice;
import com.eningqu.aipen.sdk.comm.ScanListener;

import java.util.ArrayList;
import java.util.List;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

/**
 * @Author: Qiu.Li
 * @Create Date: 2020/3/8 14:41
 * @Description: 扫描设备
 */
public class DeviceListActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener{

    private String TAG="DeviceListActivity";
    private TextView mEmptyList;
    private TextView mTitle;
    private Button mBtnCancel;
    private SwipeRefreshLayout swipeRefreshLayout;

    private List<NQDeviceBase> deviceList;
    private DeviceAdapter deviceAdapter;

    private Handler handler = new Handler();

    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private static final String tag = "test";
    private Context context;
    private UsbManager usbManager;
    private UsbDevice usbDevice;

    private boolean isRegisterUsbReceiver = false;

    private String SCAN_FILTER_VALUE = "P20";
    public String m_stringTerminationYes = "确定";
    public String m_stringTerminationNo = "取消 ";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LogUtils.d("onCreate");
        context = this;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_device_list);
        usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

//        android.view.WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
//        layoutParams.gravity = Gravity.TOP;
//        layoutParams.y = 200;

        mBtnCancel = (Button) findViewById(R.id.btn_cancel);
        mTitle = (TextView) findViewById(R.id.title_devices);
        mEmptyList = (TextView) findViewById(R.id.empty);
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);

        if(PenCtrlSdkManager.getInstance().getConnType()== NQPenSDK.CONN_TYPE.USB){

            mTitle.setText("USB设备列表");
        } else {

            mTitle.setText("蓝牙设备列表");
        }

        mBtnCancel.setText(R.string.scan);
        mEmptyList.setText(R.string.empty);
        mEmptyList.setVisibility(View.GONE);

        //设置下拉刷新的箭头颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light);
        //设置下拉刷新的背景颜色为白色
        swipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        swipeRefreshLayout.setOnRefreshListener(this);

        /**
         * 取消下拉刷新的按钮事件监听
         */
        mBtnCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NQPenSDK.getInstance().isScanning()) {

                    PenCtrlSdkManager.getInstance().stopScan();

                    mBtnCancel.setText(R.string.scan);
                    mEmptyList.setText(R.string.empty);
                    mEmptyList.setVisibility(View.GONE);
                } else {
                    deviceList.clear();
                    deviceAdapter.notifyDataSetChanged();

                    int ret = PenCtrlSdkManager.getInstance().startScanDevice();
                    if( ret== ErrorCode.SCAN_OK){
                        mBtnCancel.setText(R.string.cancel);
                        mEmptyList.setText(R.string.scanning);
                        mEmptyList.setVisibility(View.VISIBLE);
                    } else {
                        ToastUtils.showShort("error = "+ret);
                    }
                }
            }
        });

        //返回主页面
        findViewById(R.id.btn_back).setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                //返回
                finish();
            }
        });

        //设置过滤的按钮
        findViewById(R.id.btn_filter).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showEditFilterDialog();
            }
        });

        //初始化设备列表
        populateList();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //IntentFilter的使用？？？
        IntentFilter filter = new IntentFilter();
        filter.addAction(Const.Broadcast.ACTION_FIND_START);
        filter.addAction(Const.Broadcast.ACTION_FIND_STOP);
        filter.addAction(Const.Broadcast.ACTION_CONNECTED);
        filter.addAction(Const.Broadcast.ACTION_FIND_ERROR);
        filter.addAction(Const.Broadcast.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(Const.Broadcast.ACTION_USB_DEVICE_ATTACHED);
        registerReceiver(broadcastReceiver, filter);
        //设置扫描监听器
        Log.i(TAG, "onCreate: 监听器");
        PenCtrlSdkManager.getInstance().setScanListener(mScanListener);
        //设置蓝牙扫描过滤器，可以过滤YS或者P20开头的蓝牙名称
        PenCtrlSdkManager.getInstance().setBtScannerFilterValue("");
    }

    @Override
    protected void onResume() {
        super.onResume();

        //返回当前连接的设备
        if(PenCtrlSdkManager.getInstance().getCurNQDev()!=null){
            deviceList.clear();
            deviceList.add(PenCtrlSdkManager.getInstance().getCurNQDev());

            deviceAdapter.notifyDataSetChanged();
        } else {
            //搜索设备
            PenCtrlSdkManager.getInstance().startScanDevice();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.d("onDestroy");

        //反注册广播
        unregisterReceiver(broadcastReceiver);
        if(isRegisterUsbReceiver){
            unregisterReceiver(mUsbPermissionReceiver);
        }

        //清空message消息
        handler.removeCallbacks(runnable);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            runOnUiThread(() -> {

                mBtnCancel.setText(R.string.scan);
                mEmptyList.setText(R.string.empty);
                mEmptyList.setVisibility(View.GONE);
                swipeRefreshLayout.setRefreshing(false);

                deviceAdapter.notifyDataSetChanged();
            });
        }
    };

    /**
     * 蓝牙名称过滤对话框
     */
    private void showEditFilterDialog(){

        LayoutInflater factory = LayoutInflater.from(this);//提示框
        final View view = factory.inflate(R.layout.dialog_scanner_filter, null);//这里必须是final的
        final EditText edit = (EditText)view.findViewById(R.id.editBleName);//获得输入框对象
        edit.setText(SCAN_FILTER_VALUE);

        new AlertDialog.Builder(this)
                .setTitle("过滤名称")
                .setView(view)
                .setPositiveButton(m_stringTerminationYes, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String keyName = edit.getText().toString().trim();
                        SCAN_FILTER_VALUE = keyName;

                        PenCtrlSdkManager.getInstance().setBtScannerFilterValue(keyName);
                    }
                })
                .setNegativeButton(m_stringTerminationNo, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }

    /**
     * 点击设备，选中设备
     */
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (NQPenSDK.getInstance().isScanning()) {
                mBtnCancel.setText(R.string.scan);
                mEmptyList.setText(R.string.empty);
                mEmptyList.setVisibility(View.GONE);

                PenCtrlSdkManager.getInstance().stopScan();
            }
            Intent result = new Intent();
            if (position >= 0 && position < deviceList.size()) {
                NQDeviceBase deviceInfo = deviceList.get(position);

                PenCtrlSdkManager.getInstance().setCurNQDev(deviceInfo);
//                resultesult.putExtra(getString(R.string.KEY_DEVICE_INFO_1), deviceInfo.getType());
//                result.putExtra(getString(R.string.KEY_DEVICE_INFO_2), deviceInfo);
//                setResult(Activity.RESULT_OK, result);

                //区分usb和蓝牙，并连接设备
                if(PenCtrlSdkManager.getInstance().getConnType()== NQPenSDK.CONN_TYPE.USB){

                    usbDevice = ((NQUsbDevice)deviceInfo).getDevice();
                    if(checkUsbDevicePermission()){
                        PenCtrlSdkManager.getInstance().connect(PenCtrlSdkManager.getInstance().getCurNQDev());
                        finish();
                    }
                } else {
                    PenCtrlSdkManager.getInstance().connect(PenCtrlSdkManager.getInstance().getCurNQDev());
                    finish();
                }
            }
        }
    };

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {

//        PenCtrlSdkManager.getInstance().stopSearchPeripheralsList();
        deviceList.clear();
        deviceAdapter.notifyDataSetChanged();

        PenCtrlSdkManager.getInstance().startScanDevice();
        mBtnCancel.setText(R.string.cancel);
        mEmptyList.setText(R.string.scanning);
        mEmptyList.setVisibility(View.VISIBLE);

        handler.postDelayed(runnable, 10000);//更新UI
    }

    /**
     * 初始化设备列表
     */
    private void populateList() {
        deviceList = new ArrayList<>();
        deviceAdapter = new DeviceAdapter(this, deviceList);

        ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(deviceAdapter);
        newDevicesListView.setOnItemClickListener(mDeviceClickListener);
    }

    boolean bDevExist = false;
    /**
     * 添加设备
     */
    private void addDevice(NQDeviceBase nqDeviceBase) {
        if (null==nqDeviceBase)
            return;

        if("bt".equals(nqDeviceBase.getType())){

            NQBtDevice nqBtDevice = (NQBtDevice)nqDeviceBase;
            bDevExist = false;
            if(null!=nqBtDevice){

                for(NQDeviceBase deviceBase:deviceList){
                    NQBtDevice btDevice = (NQBtDevice) deviceBase;
                    if(null!=btDevice && btDevice.mac.equals(nqBtDevice.mac)){
                        bDevExist = true;
                    }
                }
            }
            if(bDevExist){
                return;
            }
        }
        deviceList.add(nqDeviceBase);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                deviceAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 获取绑定的蓝牙设备
     * @return
     */
//    private int getBondedDevices() {
//        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
//        Set<BluetoothDevice> tempDevices = bluetoothManager.getAdapter().getBondedDevices();
//        if (tempDevices == null || tempDevices.size() <= 0)
//            return -1;
//        for (Iterator<BluetoothDevice> iterator = tempDevices.iterator(); iterator.hasNext(); ) {
//            addDevice(iterator.next(), 0);
//        }
//        return 0;
//    }

    /**
     * 获取USB设备
     */
    private void getUsbDevice(){
//        PenCtrlManager.getInstance().getUsbDevice();
    }

    /**
     * 扫描监听
     */
    ScanListener mScanListener = new ScanListener() {
        @Override
        public void onScanStart() {
            mBtnCancel.setText(R.string.cancel);
            mEmptyList.setText(R.string.scanning);
            mEmptyList.setVisibility(View.VISIBLE);

            deviceList.clear();
            deviceAdapter.notifyDataSetChanged();

            Log.i(TAG, "onScanStart: 开始");
            handler.postDelayed(runnable, 10000);
            swipeRefreshLayout.setRefreshing(true);
        }

        @Override
        public void onScanStop() {

            Log.i(TAG, "onScanStop: 停止");
            handler.removeCallbacks(runnable);
            handler.postDelayed(runnable, 0);
        }

        @Override
        public void onReceiveException(int error, String message) {
            LogUtils.e("error="+error+", message="+message);
        }

        @Override
        public void onScanResult(final NQDeviceBase device) {

            Log.i(TAG, "onScanResult: device"+device.exInfo);
            //搜索到一个设备
            addDevice(device);
        }
    };

    //判断usb设备是否已获取了授权
    private boolean checkUsbDevicePermission() {
        if (null != usbManager && null != usbDevice && !usbManager.hasPermission(usbDevice)) {
            Log.d(tag, "usb设备未授权，弹出对话框请求授权");
            ToastUtils.showShort("请授予访问权限");
            IntentFilter filter2 = new IntentFilter(ACTION_USB_PERMISSION);
            context.registerReceiver(mUsbPermissionReceiver, filter2);
            PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_UPDATE_CURRENT);
            usbManager.requestPermission(usbDevice, pi);

            isRegisterUsbReceiver = true;
            return false;
        }
        return true;
    }

    /**
     * usb权限的广播
     */
    private BroadcastReceiver mUsbPermissionReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
                if (granted) {
                    Log.d(tag, "获得了usb使用权限，去初始化设备");
                    ToastUtils.showShort("授权成功");
                    //获得了usb使用权限，去初始化设备
//                    usbDeviceInit(device);
                    PenCtrlSdkManager.getInstance().connect(PenCtrlSdkManager.getInstance().getCurNQDev());
                    finish();
                } else {
                    Log.e(tag, "device get permission granted is false");
                    ToastUtils.showShort("授权失败");
                }
            }
        }
    };

    /**
     * usb连接和蓝牙连接的广播
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(Const.Broadcast.ACTION_USB_DEVICE_ATTACHED)){

                deviceList.clear();
                deviceAdapter.notifyDataSetChanged();

                PenCtrlSdkManager.getInstance().startScanDevice();

                mBtnCancel.setText(R.string.cancel);
                mEmptyList.setText(R.string.scanning);
                mEmptyList.setVisibility(View.VISIBLE);
            } else if(intent.getAction().equals(Const.Broadcast.ACTION_USB_DEVICE_DETACHED)){

                PenCtrlSdkManager.getInstance().stopScan();
                mBtnCancel.setText(R.string.scan);
                mEmptyList.setText(R.string.empty);
                mEmptyList.setVisibility(View.GONE);

                deviceList.clear();
                deviceAdapter.notifyDataSetChanged();
            } else if(intent.getAction().equals(Const.Broadcast.ACTION_CONNECTED)){

                DeviceListActivity.this.finish();
            }
        }
    };
}
